package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.bomp.facade.BompMchntInspectService;
import cc.rengu.igas.bomp.facade.bean.InspectTaskDetailBean;
import cc.rengu.igas.bomp.facade.bean.MchntInspectTaskBean;
import cc.rengu.igas.bomp.facade.bean.NeedInspectMchntInfoBean;
import cc.rengu.igas.bomp.facade.request.InspectTaskMchntListQueryRequest;
import cc.rengu.igas.bomp.facade.request.MchntInspectNoticeRequest;
import cc.rengu.igas.bomp.facade.request.MchntInspectTaskListQueryRequest;
import cc.rengu.igas.bomp.facade.response.InspectTaskMchntListQueryResponse;
import cc.rengu.igas.bomp.facade.response.MchntInspectNoticeResponse;
import cc.rengu.igas.bomp.facade.response.MchntInspectTaskListQueryResponse;
import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.redp.bizimpl.enums.BompTxnNumEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.InspectTaskDetail;
import cc.rengu.redp.bizimpl.upmp.domain.InspectTaskInfo;
import cc.rengu.redp.bizimpl.upmp.dao.InspectTaskInfoMapper;
import cc.rengu.redp.bizimpl.upmp.service.IInspectTaskDetailService;
import cc.rengu.redp.bizimpl.upmp.service.IInspectTaskInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpBMchntBaseInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Service
public class InspectTaskInfoServiceImpl extends ServiceImpl<InspectTaskInfoMapper, InspectTaskInfo> implements IInspectTaskInfoService {

    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;

    @Autowired
    private IInspectTaskDetailService inspectTaskDetailService;
    
    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Async
    @Override
    public void saveData(InspectTaskInfo inspectTaskInfo, List<InspectTaskDetail> inspectTaskDetails, HttpServletRequest request, String saveFlag) {
        request.getSession(false).setAttribute(saveFlag,"1");
        try {
            this.saveOrUpdate(inspectTaskInfo);
            //    inspectTaskDetailDao.save(inspectTaskDetails);
            for (int i = 0; i < inspectTaskDetails.size(); i++){
                InspectTaskDetail inspectTaskDetail = inspectTaskDetails.get(i);
                inspectTaskDetailService.saveOrUpdate(inspectTaskDetail);
            }
            request.getSession(false).removeAttribute(saveFlag);
        }catch (Exception e){
            request.getSession(false).removeAttribute(saveFlag);
            e.printStackTrace();
        }
    }

    @Override
    public IPage<MchntInspectTaskBean> findPageFromBomp(HttpServletRequest request, QueryRequest queryRequest, UpmpUserInfoVO user, BompMchntInspectService mchntInspectService, String traceNo) throws RedpException {
        Page<MchntInspectTaskBean> page = new Page<>();
        String instId = request.getParameter("instId");
        if (Common.isBlank(instId)) {
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())) {
                instId = user.getInstId();
            }
        } else {
            //非运营中心管理员使用与自己所属法人行不符的法人行号查询数据时提示异常
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())
                    && !user.isAdmin() && !instId.equals(user.getInstId())) {
                log.error("查询商户巡检任务列表请求参数与用户身份不符");
                throw new RedpException("查询商户巡检任务列表请求参数与用户身份不符");
            }
        }

        String inspectBeginTime = request.getParameter("inspectBeginTime");
        String inspectEndTime = request.getParameter("inspectEndTime");
        String empNo = request.getParameter("empNo");

        try {
            MchntInspectTaskListQueryRequest req = new MchntInspectTaskListQueryRequest();
            req.setUserId(user.getId());
            req.setStartDate(inspectBeginTime);
            req.setEndDate(inspectEndTime);
            req.setInstId(instId);
            req.setEmpNo(empNo);
            req.setPageSize(queryRequest.getPageSize());
            req.setPageIndex(queryRequest.getPageNum());
            req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mchntInspectTaskListQuery.getType(), instId,null));
            log.info("法人行[" + user.getInstId() + "],用户标识[" + req.getUserId() + "],开始时间[" + req.getStartDate() + "],结束时间[" + req.getEndDate() + "]" + BompTxnNumEnum.mchntInspectTaskListQuery.getDesc() + "交易请求报文：" + JSON.toJSONString(req));
            List<MchntInspectTaskBean> list = Lists.newArrayList();
            Result<MchntInspectTaskListQueryResponse> response = mchntInspectService.mchntInspectTaskListQuery(req);
            log.info("法人行[" + user.getInstId() + "],用户标识[" + req.getUserId() + "],开始时间[" + req.getStartDate() + "],结束时间[" + req.getEndDate() + "]" + BompTxnNumEnum.mchntInspectTaskListQuery.getDesc() + "交易返回报文：" + JSON.toJSONString(response));
            if (response.isSuccess()) {
                MchntInspectTaskListQueryResponse resp = response.getResult();
                log.info("法人行[" + user.getInstId() + "],用户标识[" + req.getUserId() + "],开始时间[" + req.getStartDate() + "],结束时间[" + req.getEndDate() + "]" + BompTxnNumEnum.mchntInspectTaskListQuery.getDesc() + "交易成功");
                if (Common.isNotBlank(resp) && CollectionUtils.isNotEmpty(resp.getMchntInspectTaskList())) {
                    list = resp.getMchntInspectTaskList();
                }
                page.setRecords(list);
                page.setTotal(list.size());
                return page;
            } else {
                log.info("法人行[" + user.getInstId() + "],用户标识[" + req.getUserId() + "],开始时间[" + req.getStartDate() + "],结束时间[" + req.getEndDate() + "]" + BompTxnNumEnum.mchntInspectTaskListQuery.getDesc() + "交易没有获得返回信息");
                page.setRecords(list);
                page.setTotal(0);
                return page;
            }
        } catch (Exception e) {
            log.error("查询商户巡检任务列表出现异常", e);
            throw new RedpException("查询商户巡检任务列表出现异常:" + e.getMessage());
        }
    }
@Override
    public IPage<NeedInspectMchntInfoBean> needInspectMchntListQuery(HttpServletRequest request, QueryRequest queryRequest, UpmpUserInfoVO user, BompMchntInspectService mchntInspectService, String traceNo) throws RedpException {
        Page<NeedInspectMchntInfoBean> page= new Page<>();
        String instId = request.getParameter("instId");
        if (Common.isBlank(instId)) {
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())) {
                instId = user.getInstId();
            }
        } else {
            //非运营中心管理员使用与自己所属法人行不符的法人行号查询数据时提示异常
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())
                    && !user.isAdmin() && !instId.equals(user.getInstId())) {
                log.error("查询商户巡检任务列表请求参数与用户身份不符");
                throw new RedpException("查询商户巡检任务列表请求参数与用户身份不符");
            }
        }

        String inspectTaskType = request.getParameter("inspectTaskType");
        if (StringUtils.isBlank(inspectTaskType)) {
            log.info("巡检任务列表查询参数[inspectTaskType]为空，无法检索数据");
            throw new RedpException("巡检任务列表查询参数[inspectTaskType]为空，无法检索数据");
        }
        String industryType = request.getParameter("industryType");
        String mchntAttr = request.getParameter("mchntAttr");
        String signInstId = request.getParameter("signInstId");
        String mchntType = request.getParameter("mchntType");
        String mchntLevel = request.getParameter("mchntLevel");
        String mchntNo = request.getParameter("mchntNo");
        String spotCheckMchntNum = request.getParameter("spotCheckMchntNum");
        String spotCheckMethod = request.getParameter("spotCheckMethod");
        String lowVolumeMonth = request.getParameter("lowVolumeMonth");
        String lowVolumeLessThan = request.getParameter("lowVolumeLessThan");
        String riskLevel = request.getParameter("riskLevel");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String inspectType = request.getParameter("inspectTp");

        try {
            InspectTaskMchntListQueryRequest req = new InspectTaskMchntListQueryRequest();
            req.setUserId(user.getId());
            req.setInspectTaskType(inspectTaskType);
            req.setIndustryType(industryType);
            req.setMchntAttr(mchntAttr);
            req.setSignInstId(signInstId);
            req.setMchntType(mchntType);
            req.setMchntLevel(mchntLevel);
            req.setMchntNo(mchntNo);
            req.setSpotCheckMchntNum(spotCheckMchntNum);
            req.setSpotCheckMethod(spotCheckMethod);
            req.setLowVolumeMonth(lowVolumeMonth);
            req.setLowVolumeLessThan(lowVolumeLessThan);
            req.setRiskLevel(riskLevel);
            req.setStartDate(startDate);
            req.setEndDate(endDate);
            req.setInspectType(inspectType);

            req.setPageSize(queryRequest.getPageSize());
            req.setPageIndex(queryRequest.getPageNum());
            req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.needInspectMchntListQuery.getType(), instId,null));
            List<NeedInspectMchntInfoBean> list = Lists.newArrayList();
            log.info("{}交易请求报文：{}", BompTxnNumEnum.needInspectMchntListQuery.getDesc(), JSON.toJSONString(req));
            Result<InspectTaskMchntListQueryResponse> response = mchntInspectService.needInspectMchntListQuery(req);
            log.info("{}交易应答报文：{}", BompTxnNumEnum.needInspectMchntListQuery.getDesc(), JSON.toJSONString(response));
            if (response.isSuccess()) {
                InspectTaskMchntListQueryResponse resp = response.getResult();
                if (Common.isNotBlank(resp) && CollectionUtils.isNotEmpty(resp.getNeedInspectMchntInfoList())) {
                    list = resp.getNeedInspectMchntInfoList();
                }
                page.setRecords(list);
                page.setTotal(resp.getTotalRows());
                return page;
            } else {
                page.setRecords(list);
                page.setTotal(0);
                return page;
            }
        } catch (Exception e) {
            log.error("查询商户巡检任务列表出现异常", e);
            throw new RedpException("查询商户巡检任务列表出现异常:" + e.getMessage());
        }
    }
@Override
    public List<NeedInspectMchntInfoBean> allNeedInspectMchntListQuery(HttpServletRequest request, UpmpUserInfoVO user, BompMchntInspectService mchntInspectService, String traceNo) {
        List<NeedInspectMchntInfoBean> resultData = new ArrayList<NeedInspectMchntInfoBean>();
        int pageIndex = 0;
        int pageSize = 5000;
        String instId = request.getParameter("instId");
        if (Common.isBlank(instId)) {
            instId = user.getInstId();
        }
        String inspectTaskType = request.getParameter("inspectTaskType");
        String industryType = request.getParameter("industryType");
        String mchntAttr = request.getParameter("mchntAttr");
        String signInstId = request.getParameter("signInstId");
        String mchntType = request.getParameter("mchntType");
        String mchntLevel = request.getParameter("mchntLevel");
        String mchntNo = request.getParameter("mchntNo");
        String spotCheckMchntNum = request.getParameter("spotCheckMchntNum");
        String spotCheckMethod = request.getParameter("spotCheckMethod");
        String lowVolumeMonth = request.getParameter("lowVolumeMonth");
        String lowVolumeLessThan = request.getParameter("lowVolumeLessThan");
        String riskLevel = request.getParameter("riskLevel");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String inspectType = request.getParameter("inspectTp");

        try {
            InspectTaskMchntListQueryRequest req = new InspectTaskMchntListQueryRequest();
            req.setUserId(user.getId());
            req.setInspectTaskType(inspectTaskType);
            req.setIndustryType(industryType);
            req.setMchntAttr(mchntAttr);
            req.setSignInstId(signInstId);
            req.setMchntType(mchntType);
            req.setMchntLevel(mchntLevel);
            req.setMchntNo(mchntNo);
            req.setSpotCheckMchntNum(spotCheckMchntNum);
            req.setSpotCheckMethod(spotCheckMethod);
            req.setLowVolumeMonth(lowVolumeMonth);
            req.setLowVolumeLessThan(lowVolumeLessThan);
            req.setRiskLevel(riskLevel);
            req.setStartDate(startDate);
            req.setEndDate(endDate);
            req.setInspectType(inspectType);
            req.setPageIndex(pageIndex);
            req.setPageSize(pageSize);

            req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.needInspectMchntListQuery.getType(), instId,null));

            log.info("{}交易请求报文：{}", BompTxnNumEnum.needInspectMchntListQuery.getDesc(), JSON.toJSONString(req));
            Result<InspectTaskMchntListQueryResponse> response = mchntInspectService.needInspectMchntListQuery(req);
            log.info("{}交易应答报文：{}", BompTxnNumEnum.needInspectMchntListQuery.getDesc(), JSON.toJSONString(response));
            if (response.isSuccess()) {
                InspectTaskMchntListQueryResponse resp = response.getResult();
                if (Common.isNotBlank(resp) && CollectionUtils.isNotEmpty(resp.getNeedInspectMchntInfoList())) {
                    resultData = resp.getNeedInspectMchntInfoList();
                    int totalPage = resp.getTotalPage();
                    for(pageIndex = 1; pageIndex < totalPage; pageIndex++){
                        req.setPageIndex(pageIndex);
                        traceNo = bMchntBaseInfoService.genMerOrder(user.getInstId());
                        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.needInspectMchntListQuery.getType(), instId,null));
                        log.info("{}交易请求报文：{}", BompTxnNumEnum.needInspectMchntListQuery.getDesc(), JSON.toJSONString(req));
                        response = mchntInspectService.needInspectMchntListQuery(req);
                        log.info("{}交易应答报文：{}", BompTxnNumEnum.needInspectMchntListQuery.getDesc(), JSON.toJSONString(response));
                        if (response.isSuccess()) {
                            resp = response.getResult();
                            if (Common.isNotBlank(resp) && CollectionUtils.isNotEmpty(resp.getNeedInspectMchntInfoList())) {
                                resultData.addAll(resp.getNeedInspectMchntInfoList());
                            }
                        }
                    }
                }
            }
            return resultData;
        }catch (Exception e) {
            log.error("全部巡检获取商户号出现异常！", e);
            return resultData;
        }
    }

    /**
     * 发送巡检通知
     *
     * @param inspectTaskNo
     * @param traceNo
     * @return
     */
    @Override
    public OperationResult mchntInspectNotice(String inspectTaskNo, String traceNo, BompMchntInspectService mchntInspectService,String instId) {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        if(user.isAdmin() && Common.isBlank(instId)){
            log.info("商户巡检任务列表参数[instId]为空");
            return null;
        }else  if (!user.isAdmin() && Common.isBlank(instId)){
            instId = user.getInstId();
        }
        MchntInspectNoticeRequest req = new MchntInspectNoticeRequest();
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mchntInspectNotice.getType(), instId,null));

        req.setUserId(user.getId());
        req.setInspectTaskNo(inspectTaskNo);

        Result<MchntInspectNoticeResponse> res;
        String msgName = BompTxnNumEnum.mchntInspectNotice.getDesc();
        try {
            log.info("{}请求报文：{}", msgName, JSON.toJSONString(req));
            res = mchntInspectService.mchntInspectNotice(req);
            log.info("{}应答报文：{}", msgName, JSON.toJSONString(res));
        } catch (Exception e) {
            log.error(msgName + "处理时系统异常:[{}]", e);
            result.put("respCode", BusinessContainer.ERROR);
            result.put("respMsg", "发送巡检通知异常");
            return OperationResult.buildFailureResult(msgName + "失败", result);
        }
        if (null == res || null == res.getResult()) {
            log.error(msgName + "处理时接口调用失败:result=[{}]", JSON.toJSONString(res));
            result.put("respCode", BusinessContainer.ERROR);
            result.put("respMsg", "发送巡检通知处理时接口调用失败");
            return OperationResult.buildFailureResult(msgName + "处理时接口调用失败", result);
        }
        if (!BusinessContainer.BSPS_SUCCESS.equals(res.getResult().getRespCode())) {
            result.put("respCode", res.getResult().getRespCode());
            result.put("respMsg", res.getResult().getRespDesc());
            return OperationResult.buildFailureResult(msgName + "失败", result);
        }
        return OperationResult.buildSuccessResult("操作处理完成", result);
    }
    @Override
    public InspectTaskInfo selectByinstIdAndinspectTaskNo(String instId, String inspectTaskNo) {
        LambdaQueryWrapper<InspectTaskInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(InspectTaskInfo::getInstId,instId);
        wrapper.eq(InspectTaskInfo::getInspectTaskNo,inspectTaskNo);
        wrapper.eq(InspectTaskInfo::getInspectTaskStatus,"01");
       return this.getOne(wrapper);
    }
}
